# -*- coding: latin1 -*-
'''
Created on 10/03/2011

@author: bruno
'''

import os
from Folder import Folder
from MP3file import MP3file
from OGGfile import OGGfile


musicExtension=['mp3','ogg']
folders=[]

def createFolderList(path='d:\\pasta',folder=None):
    '''
        Search for all folders and musics files in a given path
        return the path as a Folder object and a list of folders and musics inside it.
        @return: list of Folders
    '''

    if folder is None:
        foldersPath=[]
        musicsPath=[]
        folder= Folder(name=path,folders=foldersPath,musics=musicsPath)


    for file in os.listdir(path):
        fn= os.path.normpath(os.path.normpath(os.path.join(path, file)))
        if os.path.isdir(fn):
            new_foldersPath=[]
            new_musicsPath=[]
            new_folder = Folder(name=fn,folders=new_foldersPath,musics=new_musicsPath)
            folder.folders.append(new_folder)
            createFolderList(fn, new_folder)
        else:
            music=getMusic(fn)
            if music is not None:
                folder.musics.append(music)

    return folder


def findMusicFiles(path='d:\\pasta',recursive=True,musics=None):
    '''
        Search for musics files into the given path.
        If the recursivity is True, will search in all children folders
        @return: list of MusicsFiles
    '''
    
    if musics is None:
        musics=[]
    
    for dirpath, dirnames, filenames in os.walk(path):
        for fn in filenames:
            fn=dirpath+os.path.altsep+fn
            music=getMusic(fn)
            if music is not None:
                musics.append(music)
            
        if recursive:
            for dir in dirnames:
                findMusicFiles(path=dirpath+os.path.altsep+dir,musics=musics)
                
    return musics



def getMusic(file):
    '''
        Verify if the file is a music file.
        All the files with the extension in the musicExtension is considered music file
        @return: MusicFile
    '''
    #filter the files for musics
    ext=file.split(os.path.extsep)[-1].lower()
    if (ext in musicExtension ):
        #create the Music      
        return eval(ext.upper()+'file(file)')
    return None


    


